/**
 * 本代码实现了登录的功能，输入用户名和密码，当选择数据库PC端登录的时候，还需要输入数据库服务器的IP和Port。
 */
package com.bf.zk;

import java.awt.Color;
import java.awt.Font;
import java.awt.GraphicsConfiguration;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import com.bf.tool.SetWord;
import com.bf.zk.constants.Constants;

public class UserLogin extends JFrame implements ActionListener, MouseListener {
	private static final long serialVersionUID = 1L;
	private JFrame userLonin = null; // 登录窗体
	private JTextField userName; // 用户名
	private JPasswordField userPwd; // 密码
	private final JButton loginComfirm;
	private final JButton loginCancel;
	private String logPwd = "";
	private Process p = null;
	private JLabel userLabel0;
	@SuppressWarnings("unused")
	
	private String statusInfo;
	private ImageIcon background;
	@SuppressWarnings("unused")
	private String cancelInfo;
	
	private String titleString = "";
	private Integer titleWidth = 0;
	private Integer titleCharStarX = 0;
	private Integer titleFrontSize = 35;
	

	/**
	 * 创建登录界面并初始化
	 * @throws IOException 
	 */
	public UserLogin() throws IOException {

		new SetWord();
		GraphicsConfiguration gc = getGraphicsConfiguration();
		userLonin = new JFrame("用户登录",gc);
		userLonin.setSize(720, 576);
		userLonin.setDefaultCloseOperation(3);
		userLonin.setResizable(false);
		// 居中显示
		userLonin.setLayout(null);
		// userLonin.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
		userLonin.setLocationRelativeTo(null);
		userLonin.setIconImage(Toolkit.getDefaultToolkit().createImage("./pic/Log.jpg"));
		
		userLonin.getContentPane().setBackground(Constants.mycColor);
		
		//标题
		//获取配置文件信息
		Properties props = new Properties();
        try {
            FileInputStream in = null;
            in = new FileInputStream("ui.properties");
            props.load(in);
            titleString = props.getProperty("title");
        } catch (IOException e) {
            System.err.println(e);
        }
		//35号字，1个字35
		titleWidth = titleString.length() * titleFrontSize;
		titleCharStarX = (int) (360 - (titleFrontSize/2) * titleString.length());
		userLabel0 = new JLabel(titleString);
		userLabel0.setBounds(titleCharStarX, 62, titleWidth, 50);
		userLabel0.setFont(new Font("微软雅黑", Font.BOLD, titleFrontSize));
		
		// 用户名
		JLabel userLabel = new JLabel("用 户 名:");
		userLabel.setBounds(237, 212, 130, 30);
		userLabel.setFont(new Font("微软雅黑", 0, 25));
		userName = new JTextField("admin");
		userName.setFont(new Font("微软雅黑", 0, 30));
		userName.setBorder(null);
		userName.setBackground(Color.white);
		// userName.setFocusable(new BasicComboBoxEditor());
		userName.setEditable(true);
		userName.setBounds(335, 210, 155, 40);

		// 密码
		JLabel pwdLabel = new JLabel("密     码:");
		pwdLabel.setBounds(237, 287, 130, 40);
		pwdLabel.setFont(new Font("微软雅黑", 0, 25));
		userPwd = new JPasswordField("admin");
		userPwd.setFont(new Font("微软雅黑", 0, 30));
		userPwd.setBounds(335, 289, 155, 40);
		userPwd.setBorder(null);
		// 增加确定
		loginComfirm = new JButton("登录");
		loginComfirm.setActionCommand("loginCom");
		loginComfirm.setBounds(237, 396, 90, 35);
		loginComfirm.setFont(new Font("微软雅黑", 0, 25));
		loginComfirm.setBackground(Constants.mycColor);
		this.getContentPane().add(loginComfirm);
		// 增加取消
		loginCancel = new JButton("取消");
		loginCancel.setActionCommand("loginCancel");
		loginCancel.setBounds(396, 396, 90, 35);
		loginCancel.setFont(new Font("微软雅黑", 0, 25));
		loginCancel.setBackground(Constants.mycColor);

		// 设置背景图片
				background = new ImageIcon("./pic/logo.png");// 背景图片
				JLabel label = new JLabel(background);
				// 把标签的大小位置设置为图片刚好填充整个面板
				label.setBounds(312, 490, background.getIconWidth(), background.getIconHeight());
				userLonin.getLayeredPane().add(label, new Integer(Integer.MIN_VALUE));
				userLonin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				userLonin.add(label);
		userName.addKeyListener(new KeyAdapter(){
			public void keyPressed(KeyEvent ke){
				if(ke.getKeyChar() == KeyEvent.VK_ENTER){
					loginComfirm.doClick();
				}
			}
		}) ;
		userPwd.addKeyListener(new KeyAdapter(){
			public void keyPressed(KeyEvent ke){
				if(ke.getKeyChar() == KeyEvent.VK_ENTER){
					loginComfirm.doClick();
				}
			}
		}) ;
		
		loginComfirm.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent ke) {
				if (ke.getKeyChar() == KeyEvent.VK_ENTER) {
					loginComfirm.doClick();
				}
			}
		});
		userLonin.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent ke) {
				if (ke.getKeyChar() == KeyEvent.VK_ENTER) {
					loginComfirm.doClick();
				}
			}
		});
		loginCancel.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent ke) {
				if (ke.getKeyChar() == KeyEvent.VK_ENTER) {
					loginCancel.doClick();
				}
			}
		});
		userLonin.add(userLabel0);
		userLonin.add(userLabel);
		userLonin.add(pwdLabel);
		userLonin.add(userName);
		userLonin.add(userPwd);
		userLonin.add(loginComfirm);
		userLonin.add(loginCancel);
		loginComfirm.addMouseListener(this);
		loginCancel.addMouseListener(this);

		loginComfirm.addActionListener(this);
		loginCancel.addActionListener(this);
		userLonin.setVisible(true);
		
		//弹出虚拟键盘
//		p = Runtime.getRuntime().exec("osk");
		
	}

	/**
	 * 响应窗体的按钮事件
	 */
	@SuppressWarnings("deprecation")
	@Override
	public void actionPerformed(ActionEvent e) {
		// /////////////////////////////////////用户登录操作
		// 用户登录确定
		if (e.getActionCommand().equals("loginCom")) {
			//DoLogin();
			try {
				String name=userName.getText().trim();
				String passwd=userPwd.getText().toString().trim();
				String fileName = "./sqlite/znzk.db";
				Class.forName("org.sqlite.JDBC");
				Connection conn = DriverManager.getConnection("jdbc:sqlite:" + fileName);
				Statement stmt = conn.createStatement();
				ResultSet rs = stmt
						.executeQuery("SELECT password FROM znzk_user where username='" + name + "';");
				if (rs.next()) {
					String pw = rs.getString("password"); // Column 3
					if (passwd.equals(pw)) {
						Constants.LoginName=name;
						//关闭虚拟键盘
//						p.destroy();
						DoLogin();
					} else {
						JOptionPane.showMessageDialog(userLonin, "用户名或密码错误!", "警告", JOptionPane.WARNING_MESSAGE);
						userPwd.setText("");
					}
				}else {
					JOptionPane.showMessageDialog(userLonin, "用户名或密码错误!", "警告", JOptionPane.WARNING_MESSAGE);
					userPwd.setText("");
				}
				rs.close();
				stmt.close();
				conn.close();
			} catch (Exception ae) {
				System.out.println(ae.getMessage());
				System.out.println(ae.toString());
			}
		}

		// 用户登录取消
		if (e.getActionCommand().equals("loginCancel")) {
			p.destroy();
			System.exit(0);
		}

	}

	// 主程序入口函数
	public static void main(String[] args) {
		//窗口设置成系统风格
		try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UserLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
		
		java.awt.EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					new UserLogin();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void mouseClicked(MouseEvent e) {
	}

	@Override
	public void mousePressed(MouseEvent e) {
	}

	@Override
	public void mouseReleased(MouseEvent e) {
	}

	@Override
	public void mouseEntered(MouseEvent e) {

		if (e.getSource() == loginComfirm) {
			loginComfirm.setBackground(Constants.mycColorpress);
		} else if (e.getSource() == loginCancel) {
			loginCancel.setBackground(Constants.mycColorpress);
		}
	}

	@Override
	public void mouseExited(MouseEvent e) {
		if (e.getSource() == loginComfirm) {
			loginComfirm.setBackground(Constants.mycColor);
		} else if (e.getSource() == loginCancel) {
			loginCancel.setBackground(Constants.mycColor);
		}
	}

	/**
	 * 登录成功的处理
	 */
	public void DoLogin() {
		new MainWindow(userLonin, rootPaneCheckingEnabled);
		userLonin.setVisible(false);
	}
}
